package service;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.Query;

import play.db.jpa.JPA;

import controllers.Offers;
import controllers.Requests;

import models.Handshake;
import models.Offer;
import models.CreditType;
import models.Service;
import models.Service.Status;
import models.ServiceHasParticipants;

public class CreditManager {
	public static double INITIAL_BALANCE = 5000.0;
	public static double MAX_BALANCE = INITIAL_BALANCE * 2;
	public static int INITIAL_REPUTATION = 3;
	private static int BasePoint = 100;
	private static int AttendeePoint = 5;
	private static int numberOfOfferers = 1;
	private static int numberOfRequesters = 1;
	private static double duration = 0; 

	
	//3 Overloads for Handshake, Offer and Request
		//Handshake
    public static CreditType getService(Service s) {

    	int currentNumberOfParticipants = 1;
    	if(s.status == Service.Status.CREATED)
    	//if(s.status.compareTo(Service.Status.CREATED) == 0)
    	{
    		currentNumberOfParticipants = s.minNumberOfParticipants;
    	}
    	else if(s.status == Service.Status.HANDSHAKED)
    	{
    		currentNumberOfParticipants = s.minNumberOfParticipants;
    	}
    	else
    	{
    		Query numberOfParticipant = JPA.em().createQuery("select count(*) from " + ServiceHasParticipants.class.getName() + " where service_Id=" + s.id + " and status = 1 ");
			currentNumberOfParticipants = ((Long)numberOfParticipant.getSingleResult()).intValue();
    	}
    	if (s.getClass() == models.Offer.class)
    	{
    		numberOfRequesters = currentNumberOfParticipants;
    	}
    	if (s.getClass() == models.Request.class)
    	{
    		numberOfOfferers= currentNumberOfParticipants;
    	}
    	// These parameters should be get from Handshake after MultipleAttendee implemented
    	duration = s.getDuration();
    	CreditType ct = CalculateCredit();
    	return ct;
    }
    
    public static CreditType CalculateCredit(){
    	CreditType ct = new CreditType();
    	
    	if (duration > 0)
    	{
    		if (numberOfOfferers > 0 && numberOfRequesters > 0)
    		{
    			//S = (B + (A * (N-1))) * D
    			double SocialPoint = (double)(BasePoint + (AttendeePoint * (numberOfRequesters - 1))) * duration;
    			ct.offererSocialPoint = SocialPoint / numberOfOfferers;
    			ct.requesterSocialPoint = SocialPoint / numberOfRequesters;
    		}
    	}
	
		return ct;
	}
}
